var express = require('express');
var router = express.Router();
const user = require('../models/userDetail');

const XLSX = require("xlsx");
const formidable = require('formidable')

function importExcel(filePath, callback) {
  var data = [];
  var err = null;
  try {
    // Everything went fine
    var workbook = XLSX.readFile(filePath);　//整个　excel　文档
    var sheetNames = workbook.SheetNames; //获取所有工作薄名

    //console.log(sheetNames);

    //解析
    var sheet1 = workbook.Sheets[sheetNames[0]]; //根据工作薄名获取工作薄

    /*
     sheet1['!ref']　获取工作薄的有效范围　'A1:C20'
     XLSX.utils.decode_range 将有效范围转为　range对象
     range: {s: {r:0, c:0}, e: {r:10, 3}}
     */
    var range = XLSX.utils.decode_range(sheet1['!ref']);
    // console.log("range: " + JSON.stringify(range));

    //循环获取单元格值
    for (var R = range.s.r+1; R <= range.e.r; ++R) {
      var row_value = null;
      var cell_address = {c: 0, r: R};
      var cell = XLSX.utils.encode_cell(cell_address);
      if (sheet1[cell]) //获取单元格值
          row_value = sheet1[cell].v;
        else
          continue;
      data.push(row_value);
    }
  } catch (e) {
    err = '解析出错' + e.toString();
  }
  callback(err, data);
}


// 获取上传的所有学号信息
function getInfo(req) {
  return new Promise((resolve, reject) => {
    const nums = []
    const form = new formidable.IncomingForm()
    form.parse(req, function (err, fields, files) {
      if (err) {
        reject('formidable, form.parse err', err.stack)
      }


      importExcel(files.file.path, function (err, data) {
        if (err) {
          console.log(err);
        } else {
          for (var i = 0; i < data.length; i++) {
            nums.push(String(data[i]))
          }
          // console.log("nums: " + nums);
          // console.log(nums.length);

          user.find({
            stuNo: {
              $in: nums
            }
          },{
            _id:0,
            __v:0,
            password:0,
            userGroup:0
          }, (err, docs) => {
            if (err) {
              reject({
                errno: 1,
                msg: err
              })
            } else {
              let signIn = [];
              let unSign = [];
              for(var i=0; i<docs.length;i++){
                signIn.push(docs[i].stuNo);
              }
              // console.log("sign: " + signIn);
              // console.log(signIn.length);
              for(var j=0; j<nums.length;j++){
                if(signIn.indexOf(nums[j]) === -1){
                  unSign.push(nums[j]);
                }
              }
              // console.log("unsign: " + unSign);
              //返回结果
              resolve({
                errno: 0,
                list: docs,
                unSignin: unSign
              })
            }
          })

        }
      })



    })
  })
}

router.post('/', function (req, res, next) {
  // console.log("received imgs")

  // 获取数据
  getInfo(req).then((data) => {
    // 返回结果
    res.json(data)
    res.end()
  }).catch((err) => {
    res.json(err)
    res.end()
  })



});

module.exports = router;
